package com.fly.trading.controller;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fly.trading.dao.TradingUserRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class HomeController
{
    @Autowired
    TradingUserRepository tradingUserRepository;
    
    /**
     * Spring WebFlux支持使用老的Spring MVC注解声明Reactive Controller<br>
     * Reactive Controller操作的是非阻塞的ServerHttpRequest和ServerHttpResponse
     * 
     * @param model
     * @return
     */
    @GetMapping({"/", "/list"})
    public String home(@RequestParam(defaultValue = "1") Integer pageNo, Model model)
    {
        pageNo = Math.max(0, pageNo - 1);
        Pageable pageable = PageRequest.of(pageNo, 10);
        model.addAttribute("users", tradingUserRepository.findBy(pageable));
        
        long total = tradingUserRepository.count().block(Duration.ofSeconds(3));
        model.addAttribute("total", total);
        model.addAttribute("pageNo", pageable.getPageNumber() + 1);
        model.addAttribute("totalPage", (total + 9) / 10);
        log.info("total: {}, page: {}/{} ", total, pageable.getPageNumber() + 1, (total + 9) / 10);
        return "index";
    }
}